﻿using Avalon.Core.Data;
using Avalon.Core.MVC.Attributes;
using Avalon.Core.MVC.StateBags;
using System;

namespace Avalon.Core.MVC.Actions
{
    [PipelineAction("GetEntityAction")]
    public sealed class GetEntityAction<TModel> : IPipelineAction where TModel : class, IEntity, new()
    {
        public int Index { get; set; }
        public void Execute(IEntityBag<TModel> stateBag)
        {
            try
            {
                Guid id = Guid.Empty;
                if (stateBag.ParameterValues.ContainsKey("id")) id = Guid.Parse(stateBag.ParameterValues["id"].ToString());
                // if id is empty then return new TModel
                if (id == Guid.Empty)
                {
                    ((IEntityBag<TModel>)stateBag).Model = new TModel();
                }
                else
                {
                    // else try and retrieve it from the database
                    IRepository<TModel> lRepository = RepositoryConfig.Initialize<TModel>();
                    ((IEntityBag<TModel>)stateBag).Model = lRepository.Get(id) ?? new TModel();
                }
            }
            catch (Exception ex)
            {
                stateBag.Error = new Exception(string.Format("Get entites name: {0}", typeof(TModel).Name), ex);
            }
        }

        public void Execute(IStateBag stateBag)
        {
            Execute((IEntityBag<TModel>)stateBag);
        }
    }
}